package com.torlesse.authdemo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.torlesse.authdemo.pojo.User;
import com.torlesse.authdemo.service.TokenService;
import com.torlesse.authdemo.utlis.jwt.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: torlesse-liang
 * @Date: 2022/02/18/23:26
 * @Description:
 */
@Service
public class TokenServiceImpl implements TokenService {
    @Override
    public String getToken(User user) {
        HashMap<String, Object> subject = new HashMap<>();
        subject.put("role","ROLE_ADMIN,ROLE_MEMBER");
        subject.put("username",user.getUsername());
        subject.put("info","expend info");
        String subjectString = JSON.toJSONString(subject);
        String token = JwtUtil.createJWT(String.valueOf(user.getId()), subjectString, JwtUtil.JWT_TTL);
        return token;
    }

    @Override
    public String getTokenInfo(String token) {
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String subject = claims.getSubject();
        HashMap<String, Object> hashMap = JSONObject.parseObject(subject, HashMap.class);
        String role = (String) hashMap.get("role");
        String info = (String) hashMap.get("info");
        return role +" "+ info;
    }
}
